<!-- 活动分享配置模块 -->
<template>
  <a-form
    ref="formRef"
    class="form"
    layout="horizontal"
    labelAlign="left"
    :hideRequiredMark="false"
    :colon="false"
    :labelCol="{ span: 24 }"
    :wrapperCol="{ span: 24 }"
    :model="model"
    :rules="props.isDetail ? [] : formRules"
  >
    <a-form-item label="首次参与福分奖励" name="isFirstJoinScore">
      <a-radio-group v-model:value="model['isFirstJoinScore']" :disabled="props.isDetail">
        <a-radio :value="0">不奖励</a-radio>
        <a-radio :value="1">首次参与奖励</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item v-if="model.isFirstJoinScore === 1" label="首次参与奖励福分" name="firstJoinScore" :wrapper-col="{ span: 12 }">
      <a-input-number v-model:value="model['firstJoinScore']" :disabled="props.isDetail" placeholder="请输入奖励福分" :min="1" :precision="0" />
    </a-form-item>
    <a-form-item label="每次参与福分奖励" name="isEveryJoinScore">
      <a-radio-group v-model:value="model['isEveryJoinScore']" :disabled="props.isDetail">
        <a-radio :value="0">不奖励</a-radio>
        <a-radio :value="1">每次参与奖励</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item v-if="model.isEveryJoinScore === 1" label="每次参与奖励福分" name="everyJoinScore" :wrapper-col="{ span: 12 }">
      <a-input-number v-model:value="model['everyJoinScore']" :disabled="props.isDetail" placeholder="请输入奖励福分" :min="1" :precision="0" />
    </a-form-item>
    <template v-if="model.isFirstJoinScore === 1 || model.isEveryJoinScore === 1">
      <a-form-item label="福分过期规则类型" name="overType">
        <a-radio-group v-model:value="model['overType']" :disabled="props.isDetail">
          <a-radio :value="0">n天后过期</a-radio>
          <a-radio :value="1">指定过期时间</a-radio>
          <a-radio :value="2">次季度首月月底失效</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="model.overType === 0" label="过期天数" name="overDays" :wrapper-col="{ span: 12 }">
        <a-input-number v-model:value="model['overDays']" :disabled="props.isDetail" placeholder="请输入过期天数" :min="1" :precision="0" />
      </a-form-item>
      <a-form-item v-if="model.overType === 1" label="过期时间" name="overTime" :wrapper-col="{ span: 12 }">
        <a-date-picker v-model:value="model['overTime']" :disabled="props.isDetail" valueFormat="YYYY-MM-DD" :disabled-date="(current)=>current && current < dayjs().endOf('day')" style="width: 100%;" />
      </a-form-item>
    </template>
    <a-form-item label="中奖概率设置" name="awardType">
      <a-radio-group v-model:value="model['awardType']" :disabled="props.isDetail">
        <a-radio :value="0">按比例中奖</a-radio>
        <a-radio :value="1">顺延中奖</a-radio>
        <a-radio :value="2">百分百中奖</a-radio>
      </a-radio-group>
      <span class="gz-tip-text">
        {{ model.awardType == 0 ? '按照实际设定的比例进行中奖，抽完特定等级的奖品后，后续抽中对应等级奖品的客户为空奖。' : model.awardType == 1 ? '按照实际设定的比例进行中奖，抽完特定奖品后，顺延一个等级进行中奖，若所有的下级奖品抽完，才会出现空奖。' : '按照实际剩余的库存量设置实时中奖率，后台设置的中奖率无效化，直到奖品抽完才会出现空奖。' }}
      </span>
    </a-form-item>
    <!-- <a-form-item label="奖品派发周期性次数限制参与" name="awardPeriodType">
      <a-radio-group v-model:value="model['awardPeriodType']" :disabled="props.isDetail">
        <a-radio :value="0">不限制</a-radio>
        <a-radio :value="1">限每日</a-radio>
        <a-radio :value="2">限每周</a-radio>
        <a-radio :value="3">限每月</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item v-if="model.awardPeriodType !== 0" label="奖品派发周期性限制次数" name="awardPeriodNum" :wrapper-col="{ span: 12 }">
      <a-input-number v-model:value="model['awardPeriodNum']" :disabled="props.isDetail" placeholder="请输入奖品派发周期性限制次数" :min="0" :precision="0" />
    </a-form-item>
    <template v-if="formRules.mchType">
      <a-form-item label="参与商户类型" name="mchType">
        <a-radio-group v-model:value="model['mchType']" :disabled="props.isDetail">
          <a-radio :value="1">按星级</a-radio>
          <a-radio :value="2">按名单</a-radio>
          <a-radio :value="3">按进件时间</a-radio>
          <a-radio :value="4">全量商户</a-radio>
          <a-radio :value="5">进件周期（月）</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="model.mchType == 1 || model.mchType == 2 || model.mchType == 3" name="mchContent" :rules="[{ required: true, validator: mchContentValidator }]">
        <a-checkbox-group v-if="model.mchType == 1" v-model:value="model['mchStarList']" :disabled="props.isDetail" :options="starOptions" />
        <a-space v-if="model.mchType == 2">
          <a type="link" href="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/template/%E5%95%86%E6%88%B7%E5%90%8D%E5%8D%95.xlsx">商户模板下载</a>
          <GzUploadExe :disabled="props.isDetail" :src="model['mchNameList']" style="flex-grow: 1;" :isNeedImport="false" @sendData="getData" />
        </a-space>
        <a-date-picker
          v-if="model.mchType == 3"
          v-model:value="model['mchTimeList']"
          :disabled="props.isDetail"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          valueFormat="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-item>
    </template> -->

    <a-form-item label="同一用户可参与次数限制" name="isOnlyOneTimes">
      <a-radio-group v-model:value="model['isOnlyOneTimes']" :disabled="props.isDetail">
        <a-radio :value="0">不限制</a-radio>
        <a-radio :value="1">限制</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item v-if="model['isOnlyOneTimes'] !== 0" label="同一用户可参与次数" name="onlyOneTimes" :wrapper-col="{ span: 12 }">
      <a-input-number v-model:value="model['onlyOneTimes']" :disabled="props.isDetail" placeholder="请输入同一用户可参与次数" :min="0" :precision="0" />
    </a-form-item>

    <a-form-item label="同一用户周期性限制参与限制" name="periodType">
      <a-radio-group v-model:value="model['periodType']" :disabled="props.isDetail">
        <a-radio :value="0">不限制</a-radio>
        <a-radio :value="1">限制每日</a-radio>
        <a-radio :value="2">限制每周</a-radio>
        <a-radio :value="3">限制每月</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item v-if="model['periodType'] !== 0" label="同一用户周期性限制参与限制次数" name="periodTimes" :wrapper-col="{ span: 12 }">
      <a-input-number v-model:value="model['periodTimes']" :disabled="props.isDetail" placeholder="请输入同一用户周期性限制参与限制次数" :min="0" :precision="0" />
    </a-form-item>

    <a-form-item label="特殊参与限制" name="specialType">
      <a-radio-group v-model:value="model['specialType']" :disabled="props.isDetail" @change="e => specialTypeChange(e)">
        <a-radio :value="0">不限制</a-radio>
        <a-radio :value="1">每周几可以参与</a-radio>
        <a-radio :value="2">特殊日期可以参与</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item v-if="model['specialType'] === 1" label="" name="specialContent" :wrapper-col="{ span: 24 }">
      <a-checkbox-group v-model:value="model['specialContent']" :disabled="props.isDetail" :options="weekOptions" />
    </a-form-item>
    <a-form-item v-if="model['specialType'] === 2" label="" name="specialContent" :wrapper-col="{ span: 24 }">
      <div style="display: flex;gap: 20px;align-items: flex-start;">
        <a-date-picker
          v-model:value="model['allowSpecialDate']"
          :disabled="props.isDetail"
          style="width: 200px;"
          value-format="YYYY-MM-DD"
          :disabled-date="(current)=>disabledDate(current,model.specialContent)"
          @change="allowSpecialDateChange"
        />
        <div v-if="model.specialContent.length !== 0" class="ant-picker select-date">
          <div v-for="(item,index) in model.specialContent" :key="index" class="select-date-item">
            <span>{{ item }}</span>
            <close-outlined v-if="!props.isDetail" @click="specialContentDeleteFunc(index)" />
          </div>
        </div>
      </div>
    </a-form-item>

    <a-form-item label="参与时间限制" name="timeType">
      <a-radio-group v-model:value="model['timeType']" :disabled="props.isDetail">
        <a-radio :value="0">不限制</a-radio>
        <a-radio :value="1">限制每个可参与的天</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item v-if="model.timeType == 1" label="" name="timeStartEnd">
      <a-time-range-picker v-model:value="model['timeStartEnd']" :disabled="props.isDetail" format="HH:mm:ss" valueFormat="HH:mm:ss" :allowClear="false" />
    </a-form-item>


    <!-- 以下是新平台新增字段 -->
    <a-form-item label="是否开启黑名单" name="hasBlacklist">
      <a-radio-group v-model:value="model['hasBlacklist']" :disabled="props.isDetail">
        <a-radio :value="0">不开启</a-radio>
        <a-radio :value="1">开启</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item v-if="model['hasBlacklist'] === 1" label="" name="blacklistRuleIdList">
      <a-checkbox-group v-model:value="model['blacklistRuleIdList']" :options="plainOptions" />
    </a-form-item>
    <a-form-item label="是否开启白名单" name="hasWhitelist">
      <a-radio-group v-model:value="model['hasWhitelist']" :disabled="props.isDetail">
        <a-radio :value="0">不开启</a-radio>
        <a-radio :value="1">开启</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item label="参与门槛限制" name="thresholdType">
      <a-radio-group v-model:value="model['thresholdType']" :disabled="props.isDetail">
        <a-radio :value="0">不限制</a-radio>
        <a-radio :value="1">限制</a-radio>
      </a-radio-group>
    </a-form-item>
    <template v-if="model['thresholdType'] !== 0">
      <a-form-item label="前多少次免费" name="thresholdFreeTimes" :wrapper-col="{ span: 12 }">
        <a-input-number v-model:value="model['thresholdFreeTimes']" :disabled="props.isDetail" placeholder="请输入前多少次免费" :min="0" :precision="0" />
      </a-form-item>
      <a-form-item label="后续需消耗多少积分可参与" name="thresholdJoinScore" :wrapper-col="{ span: 12 }">
        <a-input-number v-model:value="model['thresholdJoinScore']" :disabled="props.isDetail" placeholder="请输入后续需消耗多少积分可参与" :min="0" :precision="0" />
      </a-form-item>
    </template>
    <a-form-item label="用户参与活动是否需要关注公众号" name="isFollowOfficial">
      <a-radio-group v-model:value="model['isFollowOfficial']" :disabled="props.isDetail">
        <a-radio :value="0">否</a-radio>
        <a-radio :value="1">是</a-radio>
      </a-radio-group>
    </a-form-item>
  </a-form>
</template>

<script setup>
import { defineProps, defineEmits, ref, defineExpose, onMounted } from 'vue'
import { useVModel } from '@/utils/useVModel.js'
import dayjs from 'dayjs'
import {$getAllGiveRule} from '@/api/activityManage/activityCreate/index'

const emits = defineEmits(['update:modelValue'])

const props = defineProps({
  // 表单绑定值
  modelValue: {
    type: Object,
    default: () => ({
      mchType: 1,  // 参与商户类型
      isFirstJoinScore: 0,  // 首次参与奖励
      isEveryJoinScore: 0,  // 每次参与奖励
      overType: 0, // 奖品过期类型
      awardType: 0, // 中奖概率设置
      // awardPeriodType: 0, // 奖品派发周期性次数限制
      // 下面是之前用户限制合并过来的
      timeStartEnd: [],
      isOnlyOneTimes: 0,
      periodType: 0,
      specialType: 0,
      timeType: 0,

      // 下面是新增字段
      hasBlacklist: 0,
      hasWhitelist: 0,
      thresholdType: 0,
      isFollowOfficial: 1,
    })
  },
  // 是否是详情
  isDetail: {
    type: Boolean,
    default: false
  },
  // 表单校验规则 使用当前组件时可以根据具体情况自定义 默认全部必填
  rules: {
    type: Object,
    default: () => ({})
  }
})

// 表单规则（总） 默认所有字段必填 根据具体活动 某些字段可以不填 需要在组件挂载时合并传递过来的规则
const formRules = ref({
  isFirstJoinScore: [{ required: true, message: '请选择首次参与奖励设置', trigger: 'blur' }],
  firstJoinScore: [{ required: true, message: '请输入首次参与奖励福分', trigger: 'blur' }],
  isEveryJoinScore: [{ required: true, message: '请选择每次参与奖励设置', trigger: 'blur' }],
  everyJoinScore: [{ required: true, message: '请输入每次参与奖励福分', trigger: 'blur' }],
  overType: [{ required: true, message: '请选择奖品过期规则类型', trigger: 'blur' }],
  overDays: [{ required: true, message: '请输入奖品过期天数', trigger: 'blur' }],
  overTime: [{ required: true, message: '请选择奖品过期时间', trigger: 'blur' }],
  awardType: [{ required: true, message: '请选择中奖概率设置', trigger: 'blur' }],
  // awardPeriodType: [{ required: true, message: '请选择奖品派发周期性次数限制', trigger: 'blur' }], // 新版本弃用暂时注释
  // awardPeriodNum: [{ required: true, message: '请输入奖品派发周期性限制次数', trigger: 'blur' }], // 新版本弃用暂时注释
  // 下面是之前用户限制合并过来的
  isOnlyOneTimes: [{ required: true }],
  periodType: [{ required: true }],
  specialType: [{ required: true }],
  timeType: [{ required: true }],
  onlyOneTimes: [{ required: true, message: '请输入同一用户可参与次数', trigger: ['blur'] }],
  periodTimes: [{ required: true, message: '请输入同一用户周期性限制参与限制次数', trigger: ['blur'] }],
  specialContent: [{ required: true, message: '请选择特殊参与限制', trigger: ['blur'] }],
  timeStartEnd: [{ required: true, message: '请选择参与时间限制', trigger: ['blur'] }],

  // 下面是新增字段
  hasBlacklist: [{ required: true, message: '请选择是否开启黑名单', trigger: 'blur' }],
  hasWhitelist: [{ required: true, message: '请选择是否开启白名单', trigger: 'blur' }],
  thresholdType: [{ required: true, message: '请选择参与门槛限制', trigger: 'blur' }],
  thresholdFreeTimes: [{ required: true, message: '请输入前多少次免费', trigger: 'blur' }],
  thresholdJoinScore: [{ required: true, message: '请输入后续需消耗多少积分可参与', trigger: 'blur' }],
  isFollowOfficial: [{ required: true, message: '请选择用户参与活动是否需要关注公众号', trigger: 'blur' }],
})

const model = useVModel(props, 'modelValue', emits)

// 表单实例
const formRef = ref()

// 传递表单默认值
onMounted(() => {
  emits('update:modelValue', props.modelValue)
  // 合并规则 以传递规则为准 主要用于部分活动并非所有字段都需要校验
  Object.assign(formRules.value, props.rules)
  getBlacklistRuleList()
})

const plainOptions = ref([])
// 获取黑名单列表
function getBlacklistRuleList(){
 $getAllGiveRule().then(res => {
    plainOptions.value = res.map(item => {
      return {
        label: item.ruleName,
        value: item.blacklistRuleId
      }
    })
  })
 
}

// 表单校验规则
function mchContentValidator() {
  const { mchType, mchNameList, mchTimeList, mchStarList } = props.modelValue
  if(mchType === 1 && mchStarList.length === 0){
    return Promise.reject('请选择参与商户星级')
  }
  if(mchType === 2 && !mchNameList){
    return Promise.reject('请上传参与商户名单')
  }
  if(mchType === 3 && !mchTimeList){
    return Promise.reject('请选择参与商户进件时间')
  }
  return Promise.resolve()
}

// 星级多选配置
const starOptions = [
  { label: '零星级', value: 0 },
  { label: '无星级', value: 1 },
  { label: '一星级', value: 2 },
  { label: '二星级', value: 3 },
  { label: '三星级', value: 4 },
  { label: '四星级', value: 5 },
  { label: '五星级', value: 6 },
]
function getData(item){
  emits('update:modelValue',{ ...props.modelValue, mchNameList: item })
}

// 规则时间选项 每个可以参与的周几
const weekOptions = [
  { label: '周一', value: '1' },
  { label: '周二', value: '2' },
  { label: '周三', value: '3' },
  { label: '周四', value: '4' },
  { label: '周五', value: '5' },
  { label: '周六', value: '6' },
  { label: '周日', value: '0' },
]
/**
 * 特殊时间参与限制
 */
function specialTypeChange(e){
  emits('update:modelValue',{ ...props.modelValue, specialType: e.target.value, specialContent: [] })
}
function allowSpecialDateChange(e){
  // 添加选择的时间
  if(e){
    emits('update:modelValue',{ ...props.modelValue, specialContent: props.modelValue.specialContent.concat(e), allowSpecialDate: null })
  }
}
const disabledDate = (current,arr) =>{ // 对已选的特殊日期不再可选
  let flag = false
  flag =  arr.some((son,index,arr) => {
    return  current.isSame(son,'day')
  })
  return flag || current < dayjs().endOf('day').subtract(1, 'day')
}
function specialContentDeleteFunc(index){ // 删除特殊日期
  emits('update:modelValue',{ ...props.modelValue, specialContent: props.modelValue.specialContent.filter((_, i) => i !== index) })
}

// 表单校验事件
async function validateFields(fields) {
  return new Promise((resolve, reject) => {
    formRef.value.validateFields(fields).then(() => {
      resolve()
    }).catch(err => {
      reject(err)
    })
  })
}
// 表单重置事件
function clearValidate() {
  if (formRef.value !== undefined) {
    formRef.value.clearValidate()
  }
}

// 暴露表单校验事件
defineExpose({
  validateFields,
  clearValidate
})

</script>

<style lang="less" scoped>
.form{
  width: 80%;
  margin-left: 20px;
  height: 100%;
  overflow-y: auto;
  &::-webkit-scrollbar{
    display: none;
  }
}
:deep(.ant-input-number) {
  width: 100%;
}
</style>